package com.apestech.formwork.run.core;

import com.apestech.formwork.xml.core.exec.SingleNode;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.run.datamapper.SingleDataMappingModule;

import java.util.ArrayList;

/**
 * 配套XML中where类型的input, output输出算法
 *
 * @author hup
 * @create 2018-04-26-10:00
 */
public class SingleWhile {
    private SingleNode node;
    private JSONObject input;
    private JSONObject output=null;
    private boolean success=true;
    private SqlSession session;
    private String error;
    private String errorId;

    public SingleWhile(SingleNode node){
        this.node=node;
    }

    public void setSqlSession(SqlSession session){
        this.session=session;
    }

    public void setInput(JSONObject input){
        this.input=input;
    }

    public void execute() throws Exception {
        JSONObject in=ExecUtil.getData((ArrayList<SingleDataMappingModule>) this.node.getParam().getInput(), this.input);
        JSONArray list= (JSONArray) ExecUtil.execProcess(this.node.getParam(), in, this, this.session);
        if(list!=null){
            this.output=new JSONObject();
            int len=list.size();
            for(int i=0; i<len; i++){
                JSONObject map= (JSONObject) list.get(i);
                JSONObject out=ExecUtil.getData((ArrayList<SingleDataMappingModule>) this.node.getParam().getOutput(), map);
                if(out!=null){
                    this.output.putAll(out);
                }
            }
        } else {
            this.success=false;
            this.error="没有符合条件的数据";
            this.errorId="SINGLE_WHILE_EMPTY";
        }
    }

    public JSONObject getOutput() {
        return output;
    }

}
